#include "systemsettingswidget.h"
#include "ui_systemsettingswidget.h"
#include "settings.h"
#include <QLineEdit>
#include <QPushButton>
#include <QCheckBox>
#include <QTextEdit>
#include <QGridLayout>
#include <QLabel>
#include <QFileDialog>
#include <QSqlQuery>
#include <QMessageBox>
#include <QCryptographicHash>
#include <QSqlError>
SystemSettingsWidget::SystemSettingsWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::SystemSettingsWidget)
{
    setFixedSize(400,600);
    ui->setupUi(this);
    createUI();
    loadSettings();
}

SystemSettingsWidget::~SystemSettingsWidget()
{
    delete ui;
}

void SystemSettingsWidget::createUI()
{
    dbPathEdit = new QLineEdit(this);
    browseBtn = new QPushButton("浏览...", this);
    oldPwdEdit = new QLineEdit(this);
    newPwdEdit = new QLineEdit(this);
    confirmPwdEdit = new QLineEdit(this);
    cacheCheckBox = new QCheckBox("记住登录信息", this);
    saveBtn = new QPushButton("保存", this);
    versionInfoEdit = new QTextEdit(this);

    oldPwdEdit->setEchoMode(QLineEdit::Password);
    newPwdEdit->setEchoMode(QLineEdit::Password);
    confirmPwdEdit->setEchoMode(QLineEdit::Password);
    versionInfoEdit->setPlainText("管理系统1.0\n 开发环境: QT C++ 6.6，Qt Creator 12.0.2，Win10");
    versionInfoEdit->setReadOnly(true);

    mainLayout = new QGridLayout(this);
    mainLayout->addWidget(new QLabel("数据库路径:", this), 0, 0);
    mainLayout->addWidget(dbPathEdit, 0, 1);
    mainLayout->addWidget(browseBtn, 0, 2);
    mainLayout->addWidget(new QLabel("旧密码:", this), 1, 0);
    mainLayout->addWidget(oldPwdEdit, 1, 1, 1, 2);
    mainLayout->addWidget(new QLabel("新密码:", this), 2, 0);
    mainLayout->addWidget(newPwdEdit, 2, 1, 1, 2);
    mainLayout->addWidget(new QLabel("确认密码:", this), 3, 0);
    mainLayout->addWidget(confirmPwdEdit, 3, 1, 1, 2);
    mainLayout->addWidget(cacheCheckBox, 4, 0, 1, 3);
    mainLayout->addWidget(saveBtn, 5, 1, 1, 2);
    mainLayout->addWidget(versionInfoEdit, 6, 0, 1, 3);

    setLayout(mainLayout);

    connect(browseBtn, &QPushButton::clicked, this, &SystemSettingsWidget::browseDatabasePath);
    connect(saveBtn,&QPushButton::clicked,this,&SystemSettingsWidget::saveSettings);
}

void SystemSettingsWidget::browseDatabasePath()
{
    QString path = QFileDialog::getSaveFileName(
        this,
        tr("选择数据库文件"),  // 使用tr支持多语言
        QString(),           // 默认路径
        tr("SQLite数据库 (*.db *.sqlite)")
        );

    if (!path.isEmpty()) {
        dbPathEdit->setText(path);

        // 可选：自动添加扩展名
        // if (!path.endsWith(".db", Qt::CaseInsensitive) &&
        //     !path.endsWith(".sqlite", Qt::CaseInsensitive)) {
        //     path += ".db";
        //     dbPathEdit->setText(path);
        // }
    }
}

void SystemSettingsWidget::loadSettings()
{
    // 获取单例实例
    Settings& settings = Settings::instance();

    // 加载数据库路径（添加空值检查）
    if (QLineEdit* dbEdit = dbPathEdit) {
        QString dbPath = settings.getDatabasePath();
        dbEdit->setText(dbPath.isEmpty() ? tr("未设置数据库路径") : dbPath);
    }

    // 加载缓存设置（添加类型安全转换）
    if (QCheckBox* cacheBox = cacheCheckBox) {
        bool cacheEnabled = settings.getCacheEnabled();
        cacheBox->setChecked(cacheEnabled);

        // 可选：根据设置启用/禁用相关控件
        // toggleCacheRelatedWidgets(cacheEnabled);
    }

    // 可扩展：加载其他设置项
    // loadOtherSettings(settings);
}

void SystemSettingsWidget::updatePassword() {
    if (!validatePasswordChange()) return;

    QString newHash = QString(QCryptographicHash::hash(
                                  newPwdEdit->text().toUtf8(),
                                  QCryptographicHash::Sha256
                                  ).toHex());

    QSqlQuery query;
    query.prepare("UPDATE users SET password = ? WHERE username = ?");
    query.addBindValue(newHash);
    query.addBindValue(Settings::instance().getLastUser());

    if (!query.exec()) {
        QMessageBox::critical(this, "错误", "密码更新失败: " + query.lastError().text());
        return;
    }
    QMessageBox::information(this, "提示", "密码更新成功");
}

bool SystemSettingsWidget::validatePasswordChange() {
    if (newPwdEdit->text() != confirmPwdEdit->text()) {
        QMessageBox::warning(this, "错误", "新密码与确认密码不一致");
        return false;
    }
    QString currentUser = Settings::instance().getLastUser();
    if (currentUser.isEmpty()) {
        QMessageBox::warning(this, "错误", "未找到当前用户");
        return false;
    }
    QSqlQuery query;
    query.prepare("SELECT password FROM users WHERE username = ?");
    query.addBindValue(currentUser);
    if (!query.exec() || !query.next()) {
        QMessageBox::critical(this, "错误", "数据库查询失败: " + query.lastError().text());
        return false;
    }
    QString storedHash = query.value(0).toString();
    QString inputHash = QString(QCryptographicHash::hash(
                                    oldPwdEdit->text().toUtf8(),
                                    QCryptographicHash::Sha256
                                    ).toHex());
    if (storedHash != inputHash) {
        QMessageBox::warning(this,"错误","旧密码不正确");
        return false;
    }
    return true ;
}

void SystemSettingsWidget::saveSettings() {
    QString newDbPath = dbPathEdit->text();
    Settings::instance().setDatabasePath(newDbPath);
    Settings::instance().setCacheEnabled(cacheCheckBox->isChecked());

    if (!newPwdEdit->text().isEmpty()) {
        updatePassword();
    }

    if (newDbPath != Settings::instance().getDatabasePath()) {
        QMessageBox::information(this, "提示", "数据库路径修改将在重启后生效");
    }
}
